package com.example.musiccommunity.UserPage;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.musiccommunity.MainActivity;
import com.example.musiccommunity.R;
import com.example.musiccommunity.bean.Song;

import java.io.File;
import java.io.IOException;

public class PlayLocalMusic extends AppCompatActivity {
    private MediaPlayer mediaPlayer;
    private boolean isPlaying = false; // 用于跟踪播放状态
    private Toolbar toolbar;
    private ImageView img;
    private TextView name;
    private TextView artist;
    private TextView now;
    private SeekBar progressBar;
    private TextView total;
    private ImageView play;



    private Runnable updateSeekBar;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_local_music);
        toolbar = findViewById(R.id.toolbar);
        img = findViewById(R.id.img);
        name = findViewById(R.id.name);
        artist = findViewById(R.id.artist);
        now = findViewById(R.id.now);
        progressBar = findViewById(R.id.seekbar);
        total = findViewById(R.id.total);
        play = findViewById(R.id.play);
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        String fileNamePrefix = getIntent().getStringExtra("name");
        initializeMediaPlayer(fileNamePrefix);
        for (Song s: MainActivity.songs
        ) {
            if(s.getRawResId().equals(getIntent().getStringExtra("name"))){
                name.setText(s.getName()+" - "+s.getArtist());
                artist.setText("来自专辑《"+s.getAlbum()+"》");
                break;
            }
        }

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null) {
                    if (isPlaying) {
                        mediaPlayer.pause();
                        isPlaying = false;
                        play.setImageDrawable(getDrawable(R.drawable.play));
                    } else {
                        mediaPlayer.start();
                        isPlaying = true;
                        play.setImageDrawable(getDrawable(R.drawable.pause));
                    }
                }
            }
        });

        progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    // 根据进度调整播放位置
                    int duration = mediaPlayer.getDuration();
                    int newPosition = (int) (((float) progress / 100) * duration);
                    mediaPlayer.seekTo(newPosition);
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 停止自动更新进度条
                handler.removeCallbacks(updateSeekBar);
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 恢复自动更新进度条
                handler.post(updateSeekBar);
            }
        });
        // 设置 SeekBar 的最大值
        progressBar.setMax(100);
        // 更新 SeekBar 的进度
        updateSeekBar = new Runnable() {
            @Override
            public void run() {
                if (mediaPlayer!=null && mediaPlayer.isPlaying()   ) {
                    int currentPosition = mediaPlayer.getCurrentPosition();
                    int duration = mediaPlayer.getDuration();

                    // 计算当前进度百分比
                    if (duration > 0) {
                        int progress = (int) (((float) currentPosition / duration) * 100);
                        progressBar.setProgress(progress);
                    }

                    //显示总时长
                    int minute = duration/1000/60;
                    int second = duration/1000%60;
                    String strMinute = "";
                    String strSecond = "";
                    if(minute<10){
                        strMinute = "0"+minute;
                    }else{
                        strMinute = minute + "";
                    }
                    if(second<10){
                        strSecond = "0"+second;
                    }else{
                        strSecond = second + "";
                    }
                    //显示总时长结束
                    total.setText(strMinute+":"+strSecond);
                    //显示播放时长开始
                    minute = currentPosition/1000/60;
                    second = currentPosition/1000%60;
                    if(minute<10){
                        strMinute = "0"+minute;
                    }else{
                        strMinute = minute + "";
                    }
                    if(second<10){
                        strSecond = "0"+second;
                    }else{
                        strSecond = second + "";
                    }
                    now.setText(strMinute+":"+strSecond);
                    //播放时长结束

//                    if(currentPosition>=duration-1){
//                        next.performClick();
//                    }
                }
                handler.postDelayed(this, 100);
            }
        };
        // 开始更新进度条
        handler.post(updateSeekBar);
    }
    private void initializeMediaPlayer(String fileNamePrefix) {
        File internalDir = getApplicationContext().getFilesDir();
        File file = new File(internalDir, fileNamePrefix + ".mp3");
        if (file.exists()) {
            mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(file.getAbsolutePath());
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        // 在 prepare() 完成后自动播放
                        mediaPlayer.start();
                        isPlaying = true;
                        play.setImageDrawable(getDrawable(R.drawable.pause));
                    }
                });
                mediaPlayer.prepareAsync(); // 使用异步准备，避免阻塞主线程
            } catch (IOException e) {
                Log.e("AudioPlayer", "Error playing audio file", e);
            }
        } else {
            Log.d("AudioPlayer", "Audio file does not exist");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}